package com.yurembo.DAO;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.yurembo.entity.Goods;

@Component
public class GoodsDAOImpl implements GoodsDAO {

	@Autowired
	SessionFactory sessionFactory;
	
	@Override
    public void addGoods(Goods goods) {
        try {
            sessionFactory.getCurrentSession().saveOrUpdate(goods);
        } catch (Exception e) {
            System.err.println("Error insert " + e);
        } 
    }
 
    @Override
    public void remove(Goods goods) {
        try {
            sessionFactory.getCurrentSession().delete(goods);
        } catch (Exception e) {
            System.err.println("Error remove  " + e);
        } 
    }
 
    @Override
    public List<Goods> getAllGoods() {
        List<Goods> goods = new ArrayList<>();
        try {
            Criteria criteria = sessionFactory.getCurrentSession()
            		.createCriteria(Goods.class);
            goods.addAll(criteria.list());
        } catch (Exception e) {
            System.err.println("Error get all  " + e);
        } 
        return goods;
    }
 
    @Override
    public Goods getGoodsById(long id) {
        Goods goods = new Goods();
        try {
            goods = (Goods) sessionFactory.getCurrentSession()
            		.load(Goods.class, id);
        } catch (Exception e) {
            System.err.println("Error get by id: " + e);
        } 
        return goods;
    }
}
